<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle" @click="gotoUrl(obj)"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';

// import { cardDataLoad, boardLoad } from '@/api/share'
let defaultData = [
    {
        "name": "系列1",
        "value": "30",
        "alise": "系列1"
    },
    {
        "name": "系列2",
        "value": "20",
        "alise": "系列2"
    },
    {
        "name": "系列3",
        "value": "15",
        "alise": "系列3"
    },
    {
        "name": "系列4",
        "value": "10",
        "alise": "系列4"
    },
    {
        "name": "系列5",
        "value": "5",
        "alise": "系列5"
    }
];

export default {
    Name: "Pie",
    components: {
        echarts
    },
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        gotoUrl: Function,
    },
    data() {
        return {
            showContent: false,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 用于比对数据是否修改
            dataStr: "",
            filterForm: {
                pageInfo: {
                    pageSize: 1,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                beginTime: undefined,
                endTime: undefined,
                sortType: "1",
                dateTime: "",
            },
            timer: null,
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            if (self.chart) {
                self.chart.resize();
            }
        }, true);
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
        clearInterval(this.timer)
    },
    methods: {
        reloadInfo() {
            // 重绘
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);

            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            // #region
            const end = new Date();
            const start = new Date();
            if (this.obj.tableData.type == 0) {
                this.filterForm.isOnlie = true;

                // 查询一天内数据
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                this.filterForm.beginTime = this.parseTime(start);
                this.filterForm.endTime = this.parseTime(end);
            } else {
                this.filterForm.isOnlie = false;

                start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                this.filterForm.beginTime = this.parseTime(start, "{y}-{m}-{d}");
                this.filterForm.endTime = this.parseTime(end);

                // 刷新时间兼容处理
                if (timeSize < 60) {
                    timeSize = 60;
                }
            }
            // #endregion

            clearInterval(this.timer);
            this.getLineData();

            if (this.isReload) {
                this.timer = setInterval(() => {
                    const end = new Date();
                    this.filterForm.endTime = this.parseTime(end);

                    this.getLineData();
                }, timeSize * 1000);
            }
        },
        setStyle() {
            var style = this.obj.style;

            // #region 组件背景图或颜色
            var backgroundColor = "";
            var backgroundImage = "";

            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "";
            }
            // #endregion

            // #region 组件投影
            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }
            // #endregion

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                // backgroundImage,
                // backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }
        },
        setOptions(columns) {
            var self = this;

            // #region 系列颜色
            var colors = ['#fc8251', '#5470c6', '#91cd77', '#ef6567', '#f9c956', '#75bedc'];
            var newColors = [];
            this.obj.tableData.yList.forEach((e, index) => {
                if (e.color) {
                    newColors.push(e.color);
                }

                columns[index].alise = columns[index].name;
                // 别名设置
                if (e.isAlise && e.alise) {
                    columns[index].name = e.alise;
                }
            });
            if (this.obj.tableData.colors) {
                newColors = this.obj.tableData.colors;
            } else {
                newColors = newColors.concat(colors);
            }
            // #endregion

            // #region 标签样式
            var decimal = 0;
            if (this.obj.tableData.decimal) {
                decimal = this.obj.tableData.decimal;
            }

            var isShowLabel = false;
            if (this.obj.tableData.isShowLabel) {
                isShowLabel = this.obj.tableData.isShowLabel;
            }
            var valColor = "#333333";
            if (this.obj.tableData.valueColor) {
                valColor = this.obj.tableData.valueColor;
            }
            var valFontsize = '14px';
            if (this.obj.tableData.valuefontSize) {
                valFontsize = this.obj.tableData.valuefontSize + "px";
            }
            var valFontWeight = "";
            if (this.obj.tableData.valueFontWeight) {
                valFontWeight = this.obj.tableData.valueFontWeight;
            }
            var valFontStyle = "";
            if (this.obj.tableData.valueFontStyle) {
                valFontWeight = this.obj.tableData.valueFontStyle;
            }
            // #endregion

            // #region 其他样式
            var radius = ['0%', '65%'];
            if (this.obj.tableData.minSize >= 0 && this.obj.tableData.maxSize > this.obj.tableData.minSize) {
                radius = [`${this.obj.tableData.minSize}%`, `${this.obj.tableData.maxSize}%`];
            }

            var roseType = undefined;
            if (this.obj.tableData.isRoseType) {
                roseType = 'area';
            }

            var position = 'inside';
            if (this.obj.tableData.isShowLine) {
                position = 'outside';
            }
            var itemStyle = {};
            if (this.obj.tableData.borderWidth) {
                itemStyle = {
                    borderRadius: this.obj.tableData.borderRadius,
                    borderColor: this.obj.tableData.borderColor,
                    borderWidth: this.obj.tableData.borderWidth
                }
            }

            // #endregion

            // if (this.obj.tableData.isCircleCenter) {
            //     radius = ['22%', '62%'];
            // }

            // #region 图例 legend样式
            var isShowLegend = true;
            if (this.obj.tableData.isShowLegend != undefined) {
                isShowLegend = this.obj.tableData.isShowLegend;
            }
            var icon = "circle";
            if (this.obj.tableData.icon) {
                icon = this.obj.tableData.icon;
            }

            var textColor = "#333333";
            if (this.obj.tableData.textColor) {
                textColor = this.obj.tableData.textColor;
            }
            var textFontsize = '14px';
            if (this.obj.tableData.textfontSize) {
                textFontsize = this.obj.tableData.textfontSize + "px";
            }
            var textFontWeight = "";
            if (this.obj.tableData.textFontWeight) {
                textFontWeight = this.obj.tableData.textFontWeight;
            }
            var textFontStyle = "";
            if (this.obj.tableData.textFontStyle) {
                textFontStyle = this.obj.tableData.textFontStyle;
            }

            // var legendWidth = '100px';
            // if (this.obj.tableData.isNotWidth) {
            //     legendWidth = undefined;
            // }

            var orient = 'vertical';
            if (this.obj.tableData.orient) {
                orient = this.obj.tableData.orient;
            }
            var top = "";
            var left = "";
            var right = "";
            if (this.obj.tableData.leftPosition == 1) {
                if (this.obj.tableData.topPosition == 1) {
                    top = "center"
                } else if (this.obj.tableData.topPosition == 2) {
                    top = "bottom"
                } else {
                    top = "0"
                }
                left = 'center';
            } else if (this.obj.tableData.leftPosition == 2) {
                if (this.obj.tableData.topPosition == 1) {
                    top = "center"
                } else if (this.obj.tableData.topPosition == 2) {
                    top = "bottom"
                } else {
                    top = "0"
                }
                left = undefined;
                right = 0;
            } else {
                if (this.obj.tableData.topPosition == 1) {
                    top = "center"
                } else if (this.obj.tableData.topPosition == 2) {
                    top = "bottom"
                } else {
                    top = "0"
                }
                left = 'left';
            }

            // #endregion

            this.chart.setOption({
                tooltip: {
                    trigger: 'item',
                    formatter: (val) => {
                        return val.data.alise + " " + val.data.value;
                    }
                },
                color: newColors,
                legend: {
                    show: isShowLegend,
                    top: top,
                    left: left,
                    right: right,
                    orient: orient,
                    // type: 'scroll',
                    // width: legendWidth,
                    right: 10,
                    textStyle: {
                        color: textColor,
                        fontSize: textFontsize,
                        fontWeight: textFontWeight,
                        fontStyle: textFontStyle,
                    },
                    // 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow', 'none'
                    icon,
                    formatter: (val) => {
                        // console.log(index)
                        return val;
                    }
                },
                series: [
                    {
                        // left: "50%",
                        // center: ['40%', '50%'],
                        type: 'pie',
                        radius: radius,
                        data: columns,
                        roseType: roseType,
                        itemStyle,
                        label: {
                            show: isShowLabel,
                            formatter: function (param) {
                                return Number(param.value).toFixed(decimal);
                            },
                            color: valColor,
                            fontSize: valFontsize,
                            position: position,
                            fontWeight: valFontWeight,
                            fontStyle: valFontStyle,
                        },
                    }
                ]
            })
        },
        getLineData() {
            var self = this;

            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId) {
                this.showContent = true;
                this.setOptions(defaultData);
                return false;
            }
            // #endregion

            // #region 参数不完整
            var idlist = [];

            if (this.obj.tableData.yList.length == 0) {
                this.showContent = false;
                return false;
            }
            this.obj.tableData.yList.forEach(e => {
                if (e.id) {
                    idlist.push(e.id);
                }
            });
            if (idlist.length != this.obj.tableData.yList.length) {
                this.showContent = false;
                return false;
            }
            // #endregion

            this.showContent = true;
            this.filterForm.tableId = this.obj.tableData.tableId;
            this.filterForm.structureIds = idlist;

            if (this.obj.tableData.type != 1) {
                cardDataLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        var columns = [];
                        var resultData = res.data.data.dataResult;
                        resultData.columns.forEach((x, j) => {
                            columns.push({ name: x.name })
                        })
                        for (var i = 0; i < resultData.dataList[0].length; i++) {
                            columns[i].value = Number(resultData.dataList[0][i]).toFixed(self.obj.tableData.decimal);
                        }

                        this.setOptions(columns);
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            } else {
                boardLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        var columns = [];
                        var resultData = res.data.data.dataResult;
                        resultData.columns.forEach((x, j) => {
                            columns.push({ name: x.name })
                        })
                        for (var i = 0; i < resultData.dataList[0].length; i++) {
                            columns[i].value = Number(resultData.dataList[0][i]).toFixed(self.obj.tableData.decimal);
                        }
                        this.setOptions(columns);
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            }
        }
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    this.reloadInfo();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>